#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @File  : jpgToTxt.py
# @Time  : 2018/3/22  14:06
# @Author: 
# @Desc  : 


import os

import cv2

path = 'G:\lxx\imgTostr\img\\'
ascii_char = list("-@B&WM#()1B}[]?M+-.---,,,-^`.'")
txt_path = "txt"



File_Path = os.getcwd()+ '\\'+txt_path+'\\'  # 获取到当前文件的目录，并检查是否有report文件夹，如果不存在则自动新建report文件
if not os.path.exists(File_Path):
    os.makedirs(File_Path)


def funToStr(rgb):
    # print(rgb)
    length = len(ascii_char)  # 计算这些字符的长度
    # gray = int(0.2126 * rgb[2] + 0.7152 * rgb[1] + 0.0722 * rgb[0])  # 把图片的RGB值转换成灰度值
    gray = rgb
    unit = (256.0 + 1) / length  # 257/length
    return ascii_char[int(gray / unit)]  # 这个相当于是选出了灰度与哪个字符对应

def get_pic(file_name):
    file_path = path+file_name[0]+file_name[1]
    # return
    img_o = cv2.imread(file_path, 0)
    img = cv2.resize(img_o,(int(img_o.shape[1]*.5),int(img_o.shape[0] * .3)),interpolation=cv2.INTER_CUBIC)
    WIDTH = img.shape[1]
    HEIGHT = img.shape[0]
    txt = ""  # txt初始值为空
    for x in range(HEIGHT):  # 图像的高
        for y in range(WIDTH):  # 图像的宽
            # print("坐标：x",x,";y",y,img[x][y])
            the_str = funToStr(img[x][y])
            txt += the_str
        txt += '\n'
    # print(txt)
    print(file_path,"转成字符串成功！")
    with open("./"+txt_path+"/"+file_name[0]+".txt", 'w') as f:  # 文件输出
        f.write(txt)


def getFileName(f):
    fs = os.listdir(f)
    arr =[]
    for f1 in fs:
        # print(f1)
        [fname, fename] = os.path.splitext(f1)
        # print(fname)
        arr.append([fname, fename])
    return arr



def main():
    file_name_arr = getFileName(path)
    # print(type(the_file_name))
    # print(file_name_arr)
    # get_pic(file_name_arr[0])
    for file_name in file_name_arr:
        get_pic(file_name)





if __name__ == '__main__':
    main()